<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="1.5">
        <el-button size="small" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <TabRightBar :columns="columns" :filterSelected="filterSelected" @queryTable="getList" @sure="saveFields" />
    </el-row>

    <el-table class="tabs-table" ref="multipleTable" :height="height + 'px'" highlight-current-row v-loading="loading"
      border stripe :data="positionList" @selection-change="handleSelectionChange" @row-contextmenu="nodeContextmenu">
      <el-table-column fixed type="selection" width="55" align="center" />
      <el-table-column fixed type="index" width="60" align="center" label="序号" />
      <el-table-column fixed label="车牌号" width="100" sortable align="center" prop="plateNo" />
      <template v-for="(item, index) in showColumns">
        <el-table-column :label="item.label" sortable align="center" :prop="item.field" :show-overflow-tooltip="true"
          :width="_field_columns(item.field, 'field').width">
          <template v-if="item.field == 'longitude'" #default="scope">
            <span>{{ scope.row.longitude }},{{ scope.row.latitude }}</span>
          </template>
          <template v-if="item.field == 'onlineState'" #default="scope">
            <span>{{ onlineStatus(scope.row.onlineState) }}</span>
          </template>
          <template v-if="item.field == 'outageStatus'" #default="scope">
            <dict-tag :options="basic_vehicle_outage_status" :value="scope.row.outageStatus" />
          </template>
          <template v-if="item.field == 'state'" #default="scope">
            {{ accStatus(scope.row.state) }}
          </template>
        </el-table-column>
      </template>
    </el-table>
    <v-contextmenu ref="contextmenu" theme="bright">
      <v-contextmenu-item>设置停运状态</v-contextmenu-item>
      <v-contextmenu-item>轨迹跟踪</v-contextmenu-item>
      <v-contextmenu-item>实时视频</v-contextmenu-item>
      <v-contextmenu-item>视频回放</v-contextmenu-item>
      <v-contextmenu-item>轨迹回放</v-contextmenu-item>
      <v-contextmenu-item>短信下发</v-contextmenu-item>
      <v-contextmenu-item>语音对讲</v-contextmenu-item>
      <v-contextmenu-item>拍摄照片</v-contextmenu-item>
      <v-contextmenu-item>终端信息读取</v-contextmenu-item>
    </v-contextmenu>
  </div>
</template>

<script setup>
import TabRightBar from "@/components/TabRightToolbar"
import { outageList } from "@/api/safety/position";
import useSatetyMapStore from '@/store/modules/safetyMap'
import { toDirStr, kmUnit, accStatus, onlineStatus } from '@/utils/utils.js'
import { detaildPageSetting, addPageSetting, updatePageSetting } from '@/api/basic/userPageSetting.js'
const { proxy } = getCurrentInstance();
const { basic_vehicle_outage_status } = proxy.useDict('basic_vehicle_outage_status');


const positionList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const ConfigSetting = ref({})
const showColumns = ref([])
const filterSelected = ref([])
var configKey = 'outageListTable';

async function getConfig() {
  let config = await detaildPageSetting(configKey)
  if (config.data != null) {
    showColumns.value = JSON.parse(config.data.content)
    ConfigSetting.value = config.data
  }
  else {
    showColumns.value = JSON.parse(JSON.stringify(defaultColumns.value))
  }
  filterSelected.value = _getFilterSelected(showColumns.value);
}
getConfig()
function _getFilterSelected(arr = []) {
  return arr.map((item) => {
    return item.key;
  })
}
/**
 * 保存字段
 * @param {*} datas 
 */
function saveFields(datas) {
  console.log('selected', datas);
  let newColums = [];
  datas.forEach((element, index) => {
    newColums.push({
      key: element,
      label: _field_columns(element).label,
      field: _field_columns(element).field
    })
  });
  console.log('newColums', newColums)
  let parmas = {
    page: configKey,
    content: JSON.stringify(newColums)
  }
  if (typeof ConfigSetting.value.id == 'undefined') {
    addPageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
      showColumns.value = newColums
      getConfig()
    })
  } else {
    parmas.id = ConfigSetting.value.id;
    updatePageSetting(parmas).then(res => {
      proxy.$modal.msgSuccess("保存成功");
      showColumns.value = newColums
      getConfig()
    })
  }
}
var fieldColumns = {}
function _field_columns(key = '', findKey = 'key') {
  if (!fieldColumns.hasOwnProperty(findKey)) {
    fieldColumns[findKey] = {};
    columns.value.forEach((item) => {
      // console.log(item, ...arguments)
      fieldColumns[findKey][findKey + '_' + item[findKey]] = item
    })
  }
  return fieldColumns[findKey][findKey + '_' + key] ? fieldColumns[findKey][findKey + '_' + key] : '';
}
// 自编号、所属机构、运营线路、停运状态、在线状态、停运时间、定位时间、回传时间、位置、定位状态、acc状态、SIM卡号、设备编号
const defaultColumns = ref([
  { key: 0, label: `自编号`, visible: true, field: 'numbered' },
  { key: 1, label: `所属机构`, visible: true, field: 'deptName', width: 180 },
  { key: 2, label: `运营线路`, visible: true, field: 'operationRoute', width: 180 },
  { key: 3, label: `停运状态`, visible: true, field: 'outageStatus', width: 180 },
  { key: 4, label: `停运时间`, visible: true, field: 'outageTime', width: 180 },
  { key: 5, label: `定位时间`, visible: true, field: 'times', width: 180 },
  { key: 6, label: `GPS回传时间`, visible: true, field: 'onlineTime', width: 180 },
  { key: 7, label: `位置`, visible: true, field: 'location', width: 100 },
])
const columns = ref([
  { key: 0, label: `自编号`, visible: true, field: 'numbered', width: 180 },
  { key: 1, label: `所属机构`, visible: true, field: 'deptName', width: 180 },
  { key: 2, label: `运营线路`, visible: true, field: 'operationRoute', width: 180 },
  { key: 3, label: `停运状态`, visible: true, field: 'outageStatus', width: 180 },
  { key: 4, label: `停运时间`, visible: true, field: 'outageTime', width: 180 },
  { key: 5, label: `定位时间`, visible: true, field: 'times', width: 180 },
  { key: 6, label: `GPS回传时间`, visible: true, field: 'onlineTime', width: 180 },
  { key: 7, label: `位置`, visible: true, field: 'location', width: 600 },
  { key: 8, label: `定位状态`, visible: true, field: 'onlineState', width: 180 },
  { key: 9, label: `ACC状态`, visible: true, field: 'state', width: 180 },
  { key: 10, label: `SIM卡号`, visible: true, field: 'msisdn', width: 180 },
  { key: 11, label: `设备号`, visible: true, field: 'deviceCode', width: 180 },
]);
const data = reactive({
  form: {},
  queryParams: [],
});

const { queryParams, form } = toRefs(data);

/** 查询实时位置列表 */
function getList() {
  loading.value = true;
  outageList(queryParams.value).then(response => {
    positionList.value = response.data;
    loading.value = false;
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.deviceId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('/safety/position/outageExport', {
    ...queryParams.value
  }, `outageExport_${new Date().getTime()}.xlsx`)
}

getList();


const safeMapStore = useSatetyMapStore();
const selectedVehicleIds = computed(() => {
  return safeMapStore.selectedVehicleIds
})
const height = computed(() => {
  return safeMapStore.tabTableHeight
})
const currentSelectVehicleId = computed(() => {
  return safeMapStore.currentSelectVehicleId
})

function nodeContextmenu(row, column, event) {
  proxy.$refs['contextmenu'].show({ left: event.pageX, top: event.pageY })
  event.preventDefault()
}

onMounted(() => {
  window.addEventListener('click', () => {
    proxy.$refs['contextmenu'].hide()
  })
  console.log('position onMounted')
})
onUnmounted(() => {
  console.log('position onUnmounted')
})
onActivated(() => {
  // 调用时机为首次挂载
  // 以及每次从缓存中被重新插入时
  console.log('position activeted')
})

onDeactivated(() => {
  // 在从 DOM 上移除、进入缓存
  // 以及组件卸载时调用
  console.log('position unactiveted')
})
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;

  :deep(.el-row) {
    align-items: center;
  }

  :deep(.el-table) {
    background-color: #091940;
    color: #FFFFFF;
  }

  :deep(.el-table__header th) {
    background-color: #1C2F61 !important;
    color: #FFFFFF;
    border-color: #4E5A75;
  }

  :deep(.el-table .el-table__cell) {
    border-right: 1px solid #4E5A75;
    border-bottom: 1px solid #4E5A75;
  }

  :deep(.el-table.is-scrolling-left.el-table--border .el-table-fixed-column--left.is-last-column.el-table__cell) {
    border-right: 1px solid #4E5A75;
  }

  :deep(.el-table__body tr.el-table__row > td) {
    background-color: #091940;
  }

  :deep(.el-table__body tr.el-table__row--striped > td),
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped.current-row td.el-table__cell) {
    background-color: #0E204D;
  }

  :deep(.el-table__body tr.current-row >td),
  :deep(.el-table--striped .el-table__body tr.el-table__row--striped.current-row td.el-table__cell) {
    background-color: #1C2F61
  }

  :deep(.el-table__body tr.hover-row.current-row > td),
  :deep(.el-table__body tr.hover-row.el-table__row--striped.current-row > td),
  :deep(.el-table__body tr.hover-row.el-table__row--striped>td),
  :deep(.el-table__body tr.hover-row > td),
  :deep(.el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell) {
    background-color: #1C2F61;
  }
}
</style>